<template>
  <el-dialog
    class="flow-dialog"
    title="菜单"
    :model-value="visible"
    width="30%"
    destroy-on-close
    center
    modal
    :close-on-click-modal="false"
    :show-close="false"
  >
    <el-form
      ref="formRef"
      :model="menuForm"
      :rules="rules"
      label-width="100"
      label-position="left"
      inline-message
      :status-icon="true"
    >
      <el-form-item label="上级菜单" prop="parentId">
        <el-tree-select
          v-model="menuForm.parentId"
          node-key="id"
          :props="{
            value: 'id',
            label: 'label',
            children: 'children',
          }"
          highlight-current
          check-strictly
          lazy
          :disabled="!add"
          :load="loadMenuTree"
          :default-expanded-keys="ancestors"
        />
      </el-form-item>
      <el-form-item label="菜单名称" prop="label">
        <el-input
          v-model="menuForm.label"
          placeholder="请输入菜单名称"
          clearable
          maxlength="20"
        />
      </el-form-item>
      <el-space fill>
        <el-alert type="info" :closable="false">
          <p>
            注: 图标使用"Iconify"标准,详情请到
            <a href="https://icon-sets.iconify.design" target="_blank">
              https://icon-sets.iconify.design
            </a>
            查看
          </p>
        </el-alert>
        <el-form-item label="菜单图标" prop="icon">
          <el-input
            v-model="menuForm.icon"
            placeholder="请输入菜单图标code"
            clearable
            :prefix-icon="previewIcon()"
          />
        </el-form-item>
      </el-space>
      <el-form-item label="路由名称" prop="routerName">
        <el-input
          v-model="menuForm.routerName"
          placeholder="请输入路由名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="路由路径" prop="routerPath">
        <el-input
          v-model="menuForm.routerPath"
          placeholder="请输入路由路径"
          clearable
        />
      </el-form-item>
      <el-form-item label="文件路径" prop="filePath">
        <el-input
          v-model="menuForm.filePath"
          placeholder="请输入文件路径"
          clearable
        />
      </el-form-item>
      <el-form-item label="角色限制" prop="roles">
        <el-select
          v-model="roles"
          placeholder="请选择角色限制"
          collapse-tags-tooltip
          collapse-tags
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="item in rolesData"
            :key="item.id"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="权限限制" prop="permissions">
        <el-select
          v-model="permissions"
          placeholder="请选择权限限制"
          collapse-tags-tooltip
          collapse-tags
          filterable
          clearable
          multiple
        >
          <el-option
            v-for="item in permissionsData"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="menuForm.sort" :min="1" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button
          type="primary"
          :loading="loading"
          :icon="useRenderIcon('material-symbols:check')"
          @click="submit()"
        >
          保存
        </el-button>
        <el-button
          type="danger"
          :loading="loading"
          :icon="useRenderIcon('material-symbols:close')"
          @click="close()"
        >
          关闭
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { FormInstance } from "element-plus";
import { MenuModel } from "@/api/model/menuModel";
import { defineComponent, reactive, ref } from "vue";
import { message } from "@/utils/message";
import { getMenuChildren, saveMenu } from "@/api/menu";
import { getRoleAll } from "@/api/role";
import { getPermissionAll } from "@/api/permission";

const loading = ref(false);
const visible = ref(false);
const add = ref(true);
const roles = ref<string[]>([]);
const permissions = ref<string[]>([]);
const formRef = ref<FormInstance>();
const menuForm = ref<MenuModel>({});
const ancestors = ref([]);
const rootMenu = ref<MenuModel[]>([
  {
    id: "0",
    label: "根节点",
  },
]);
const rolesData = ref<any[]>([]);
const permissionsData = ref<any[]>([]);

const rules = reactive({
  label: [
    { required: true, message: "请输入菜单名称", trigger: "blur" },
    {
      min: 2,
      max: 20,
      message: "菜单名称必须在2-20个字符之间",
      trigger: "blur",
    },
  ],
  parentId: [{ required: true, message: "请选择上级菜单", trigger: "blur" }],
  icon: [{ required: true, message: "请输入图标代码", trigger: "blur" }],
  routerName: [{ required: true, message: "请输入路由名称", trigger: "blur" }],
  routerPath: [{ required: true, message: "请输入路由路径", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
});

const close = () => {
  visible.value = false;
};
const openAdd = () => {
  menuForm.value = {
    state: true,
  };
  add.value = true;
  visible.value = true;
};
const openEdit = (form: MenuModel) => {
  menuForm.value = {
    id: form.id,
    parentId: form.parentId + "",
    label: form.label,
    icon: form.icon,
    hidden: form.hidden,
    routerName: form.routerName,
    routerPath: form.routerPath,
    filePath: form.filePath,
    sort: form.sort,
  } as MenuModel;
  add.value = false;
  visible.value = true;
  ancestors.value = form.ancestors ? form.ancestors.split(",") : [];
  roles.value = form.roles ? form.roles.split(",") : [];
  permissions.value = form.permissions ? form.permissions.split(",") : [];
};
const loadMenuTree = async (node, resolve) => {
  if (node && node.level === 0) {
    resolve(rootMenu.value);
  } else {
    const data = await getMenuChildren(node.data.id);
    resolve(data);
  }
};

const previewIcon = () => {
  return useRenderIcon(menuForm.value.icon);
};

const loadRole = () => {
  getRoleAll().then(res => {
    rolesData.value = res;
  });
};
const loadPermission = () => {
  getPermissionAll().then(res => {
    permissionsData.value = res;
  });
};

export default defineComponent({
  setup(props, context) {
    function reloadList(pid) {
      context.emit("reload", pid);
    }
    function submit() {
      formRef.value.validate(valid => {
        if (valid) {
          loading.value = true;
          menuForm.value.roles = roles.value.join(",");
          menuForm.value.permissions = permissions.value.join(",");
          saveMenu(menuForm.value)
            .then(res => {
              if (res) {
                message("保存成功", { type: "success" });
                reloadList(res.parentId);
                close();
              } else {
                message("保存失败", { type: "error" });
              }
            })
            .catch(e => {
              message(e.message, { type: "error" });
            })
            .finally(() => {
              loading.value = false;
            });
        }
      });
    }
    return {
      formRef,
      rules,
      loading,
      visible,
      add,
      menuForm,
      ancestors,
      close,
      submit,
      useRenderIcon,
      loadMenuTree,
      previewIcon,
      loadRole,
      loadPermission,
      rolesData,
      permissionsData,
      roles,
      permissions,
    };
  },
  mounted() {
    loadRole();
    loadPermission();
  },
});

export function initMenuDialog() {
  return {
    openAdd,
    openEdit,
  };
}
</script>
<style scoped></style>
